import {getCurrentUserId} from './authService';

export function initWebSocket(onMessageCallback) {
    if (!('WebSocket' in window)) {
        console.error('浏览器不支持WebSocket功能');
        throw new Error('浏览器不支持WebSocket功能');
    }

    const wsUrl = `ws://localhost:8080/ws/chat`;
    const ws = new WebSocket(wsUrl);

    ws.onopen = () => {
        console.log('WebSocket连接已建立');
        // 连接建立后发送配置信息
        sendConfig(ws, {
            userId: getCurrentUserId() || '1', // 从本地存储获取用户ID，如果没有则使用默认值1
            sessionId: `session_${Date.now()}`, // 默认会话ID，实际应从调用处传入
            character: 'harry_potter', // 默认角色，实际应从调用处传入
            format: 'pcm',
            sampleRate: 16000,
            bits: 16,
            channel: 1,
            enablePunc: true
        });
    };

    ws.onmessage = (event) => {
        try {
            const data = JSON.parse(event.data);
            console.log('收到WebSocket消息:', data);
            onMessageCallback(data);
        } catch (error) {
            console.error('解析WebSocket消息失败:', error);
        }
    };

    ws.onclose = (event) => {
        console.log('WebSocket连接已关闭:', event.code, event.reason);
    };

    ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
    };

    return ws;
}

// 发送文本消息 - 保留原始函数名
// 修改：添加prompt参数
export function sendTextMessage(ws, text, userId, sessionId, character, voiceId, prompt) {
    if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
            type: 'text_message',
            text: text,
            userId: userId,
            sessionId: sessionId,
            character: character,
            voiceId: voiceId,
            prompt: prompt  // 新增：发送角色提示词
        }));
    }
}

// 发送语音聊天请求 - 保留原始函数名
// 修改：添加prompt参数
export function sendVoiceChat(ws, filePath, sessionId, userId, character, voiceId, prompt) {
    if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
            type: 'voice_chat',
            filePath: filePath,
            sessionId: sessionId,
            userId: userId,
            character: character,
            voiceId: voiceId,
            prompt: prompt  // 新增：发送角色提示词
        }));
    }
}

// 发送配置信息
export function sendConfig(ws, config) {
    if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
            type: 'config',
            config: config
        }));
    }
}

// 关闭WebSocket连接
export function closeWebSocket(ws) {
    if (ws) {
        ws.close();
    }
}

// 添加获取推荐提问的函数
export const getSuggestedQuestions = async (roleKey) => {
    try {
        const response = await instance.get(`/user/ai/suggestions/questions/${roleKey}`);
        return response;
    } catch (error) {
        console.error('获取推荐提问失败:', error);
        throw error;
    }
};